package com.shortvedio.content.service.imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shortvedio.base.mapper.*;
import com.shortvedio.base.model.po.*;
import com.shortvedio.content.dto.VideosContentDto;
import com.shortvedio.content.es.VideosContentDoc;
import com.shortvedio.content.service.VedioContentService;
import com.shortvedio.base.exception.ShortVedioPlusException;
import com.shortvedio.base.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
@Slf4j
public class VedioContentServiceImpl implements VedioContentService {

    @Autowired
    private UserLikeMapper userLikeMapper;

    @Autowired
    private UserRelationshipsMapper userRelationshipsMapper;

    @Autowired
    private UserFavoritesMapper userFavoritesMapper;

    @Autowired
    private VideosContentMapper videosContentMapper;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Autowired
    private VideosAboutMapper videosAboutMapper;

    @Autowired
    private FavoritesMapper favoritesMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private TaskVedioMapper taskVedioMapper;



    @Override
    @Transactional
    public Result addLike(Long userId, Long videoId) {
        //获取视频点赞记录是否存在
        LambdaQueryWrapper<UserLike> likeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        likeLambdaQueryWrapper.eq(UserLike::getUserId,userId).eq(UserLike::getVideoId,videoId);
        UserLike like = userLikeMapper.selectOne(likeLambdaQueryWrapper);
        if (like!=null){
            return Result.success("不用处理");
        }
        VideosContent videosContent = videosContentMapper.selectById(videoId);
        if (videosContent==null){
            return Result.error("视频没有");
        }
        //创建记录
        like = new UserLike();
        like.setUserId(userId);
        like.setVideoId(videoId);
        like.setGetId(videosContent.getUserId());
        like.setLikeTime(LocalDateTime.now());
        int insert = userLikeMapper.insert(like);
        if (insert<=0){
            Result.error("点赞失败");
        }
        //处理点赞数 加一
        Integer update = likeAbout(videoId, 1);
        if (update<=0){
            ShortVedioPlusException.cast("点赞失败");
        }
        return Result.success("点赞成功");

    }

    private Integer likeAbout(Long videoId,Integer count){//更新视频相关表中的数据--视频点赞数的更新
        LambdaQueryWrapper<VideosAbout> videosAboutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosAboutLambdaQueryWrapper.eq(VideosAbout::getVideosId,videoId);
        VideosAbout videosAbout = videosAboutMapper.selectOne(videosAboutLambdaQueryWrapper);
        videosAbout.setLikeCount(videosAbout.getLikeCount()+count);
        int update = videosAboutMapper.updateById(videosAbout);
        return update;
    }

    @Override
    @Transactional
    public Result deleteLie(Long userId, Long videoId) {
        //删除点赞
        LambdaQueryWrapper<UserLike> userLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLikeLambdaQueryWrapper.eq(UserLike::getUserId,userId).eq(UserLike::getVideoId,videoId);
        int delete = userLikeMapper.delete(userLikeLambdaQueryWrapper);
        if (delete<=0){
            return Result.error("取消点赞失败");
        }
        //更新视频相关表
        Integer update = likeAbout(videoId, -1);
        if (update<=0){
            ShortVedioPlusException.cast("取消点赞失败");
        }
        return Result.success("取消点赞");
    }

    @Override
    public Result deleteConcern(Long userId, Long targetUserId) {
        //删除关注记录表
        LambdaQueryWrapper<UserRelationships> userRelationshipsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRelationshipsLambdaQueryWrapper.eq(UserRelationships::getUserId,userId).eq(UserRelationships::getTargetUserId,targetUserId);
        int delete = userRelationshipsMapper.delete(userRelationshipsLambdaQueryWrapper);
        if (delete<=0){
            return Result.error("取消关注失败");
        }
        return Result.success("取消g关注");
    }

    @Override
    public Result AddConcern(Long userId, Long targetUserId) {//添加关注
        //查看是否有重复关注
        LambdaQueryWrapper<UserRelationships> userRelationshipsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRelationshipsLambdaQueryWrapper.eq(UserRelationships::getUserId,userId).eq(UserRelationships::getTargetUserId,targetUserId);
        UserRelationships userRelationships = userRelationshipsMapper.selectOne(userRelationshipsLambdaQueryWrapper);
        if (userRelationships!=null){
            return Result.success("不用处理");
        }
        //添加关注记录表
        userRelationships = new UserRelationships();
        userRelationships.setUserId(userId);
        userRelationships.setTargetUserId(targetUserId);
        userRelationships.setRelationTime(LocalDateTime.now());
        int insert = userRelationshipsMapper.insert(userRelationships);
        if (insert<=0){
            return Result.error("关注失败");
        }
        return Result.success("关注成功");
    }

    @Override
    @Transactional
    public Result addFavorites(Long favorites,Long userId,Long videoId) {
        //查看是否有重复的收藏数
        LambdaQueryWrapper<UserFavorites> userFavoritesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFavoritesLambdaQueryWrapper.eq(UserFavorites::getUserId,userId).eq(UserFavorites::getVideoId,videoId);
        UserFavorites userFavorites = userFavoritesMapper.selectOne(userFavoritesLambdaQueryWrapper);
        log.info("videoId:{}",userFavorites);
        if (userFavorites!=null){
            return Result.success("已经添加该收藏");
        }
        //创建收藏记录表
        userFavorites = new UserFavorites();
        userFavorites.setFavorites(favorites);
        userFavorites.setUserId(userId);
        userFavorites.setVideoId(videoId);
        userFavorites.setFavoriteTime(LocalDateTime.now());
        int insert = userFavoritesMapper.insert(userFavorites);
        if (insert<=0){
            Result.error("添加收藏失败");
        }
        //更新视频相关表中的收藏记录
        Integer update = favoritesAbout(videoId, 1);
        if (update<=0){
            ShortVedioPlusException.cast("添加收藏失败");
        }
        return Result.success("添加收藏成功");
    }

    private Integer favoritesAbout(Long videoId,Integer count){//视频相关表中收藏数的更新
        LambdaQueryWrapper<VideosAbout> videosAboutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosAboutLambdaQueryWrapper.eq(VideosAbout::getVideosId,videoId);
        VideosAbout videosAbout = videosAboutMapper.selectOne(videosAboutLambdaQueryWrapper);
        videosAbout.setFavoritesCount(videosAbout.getFavoritesCount()+count);
        int update = videosAboutMapper.updateById(videosAbout);
        return update;
    }

    @Override
    @Transactional
    public Result deleteFavorites(Long favorites, Long userId, Long videoId) {
        //根据userid，videoid，favorites查询
        LambdaQueryWrapper<UserFavorites> userFavoritesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFavoritesLambdaQueryWrapper.eq(UserFavorites::getUserId,userId).eq(UserFavorites::getVideoId,videoId)
                .eq(UserFavorites::getFavorites,favorites);
        int delete = userFavoritesMapper.delete(userFavoritesLambdaQueryWrapper);
        if (delete<=0){
            Result.error("删除收藏失败");
        }
        //更新视频相关表
        Integer update = favoritesAbout(videoId, -1);
        if (update<=0){
            ShortVedioPlusException.cast("添加收藏失败");
        }
        return Result.success("删除收藏成功");
    }

    @Override
    @Transactional
    public Result addVideoContent(VideosContentDto videosContentDto) {
        //通过视频的md值获取视频是否存在
        LambdaQueryWrapper<VideosContent> videosContentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosContentLambdaQueryWrapper.eq(VideosContent::getVideosMd,videosContentDto.getVideosMd());
        VideosContent videosContent = videosContentMapper.selectOne(videosContentLambdaQueryWrapper);
        if (videosContent!=null){
            return Result.success("已经有该视频请请勿重复添加");
        }
        //将视频的相关数据存储到数据库
        videosContent = new VideosContent();
        BeanUtils.copyProperties(videosContentDto,videosContent);
        videosContent.setUploadTime(LocalDateTime.now());
        videosContent.setStatus(0); // 开始审核
        Classify classify = classifyMapper.selectById(videosContent.getType());
        videosContent.setTypeName(classify.getName());
        int insert = videosContentMapper.insert(videosContent);
        if (insert<=0){
            throw new RuntimeException("提交失败");
        }
        //创建视频相关信息
        VideosAbout videosAbout = new VideosAbout();
        videosAbout.setVideosId(videosContent.getId());
        videosAbout.setLikeCount(0);
        videosAbout.setLookCount(0);
        videosAbout.setFavoritesCount(0);
        videosAbout.setCommentsCount(0);
        int insertAbout = videosAboutMapper.insert(videosAbout);
        if (insert<=0){
            throw new RuntimeException("提交失败");
        }
        return Result.success("提交成功");

    }

    @Override
    @Transactional
    public Result issueVideo(Long videoId, Long userId) {//发布视频
        //根据视频id，用户id和状态是否为1查询待发布视频
        LambdaQueryWrapper<VideosContent> videosContentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosContentLambdaQueryWrapper.eq(VideosContent::getUserId,userId).eq(VideosContent::getId,videoId).eq(VideosContent::getStatus,1);
        VideosContent videosContent = videosContentMapper.selectOne(videosContentLambdaQueryWrapper);
        if (videosContent==null){
            return Result.error("没有该视频请重新尝试");
        }
        videosContent.setStatus(2);
        int update = videosContentMapper.updateById(videosContent);
        if (update<=0){
            return Result.error("发布失败");
        }
        Boolean aBoolean = addVedioContentToEs(videosContent);
        if (!aBoolean){
            ShortVedioPlusException.cast("失败请重新上传");
        }
        return Result.success("发布成功");
    }

    @Override
    public void addLook(Long videoId) {
        LambdaQueryWrapper<VideosAbout> videosAboutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosAboutLambdaQueryWrapper.eq(VideosAbout::getVideosId, videoId);
        VideosAbout videosAbout = videosAboutMapper.selectOne(videosAboutLambdaQueryWrapper);
        videosAbout.setLookCount(videosAbout.getLookCount()+1);
        videosAboutMapper.updateById(videosAbout);
    }

    @Override
    @Transactional
    public Result deleteVideo(Long userId, Long videoId) throws IOException {
        VideosContent videosContent = videosContentMapper.selectById(videoId);
        if (!videosContent.getUserId().equals(userId)){
            return Result.error("你不是创建者请不用删除");
        }
        //点赞相关信息删除
        LambdaQueryWrapper<UserLike> userLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLikeLambdaQueryWrapper.eq(UserLike::getVideoId,videoId);
        int delete3 = userLikeMapper.delete(userLikeLambdaQueryWrapper);
        //收藏信息相关删除
        LambdaQueryWrapper<UserFavorites> userFavoritesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFavoritesLambdaQueryWrapper.eq(UserFavorites::getVideoId,videoId);
        int delete1 = userFavoritesMapper.delete(userFavoritesLambdaQueryWrapper);
        //相关内容删除
        LambdaQueryWrapper<VideosAbout> videosAboutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videosAboutLambdaQueryWrapper.eq(VideosAbout::getVideosId,videoId);
        int delete2 = videosAboutMapper.delete(videosAboutLambdaQueryWrapper);
        String videosMd = videosContent.getVideosMd();
        TaskVedio taskVedio = new TaskVedio();
        taskVedio.setInputkey(videosMd);
        taskVedio.setStatus(0);
        taskVedio.setCreatTime(LocalDateTime.now());
        int insert = taskVedioMapper.insert(taskVedio);
        int delete = videosContentMapper.deleteById(videoId);
        deleteVideo(videoId);
        return Result.success("删除成功");
    }

    private void deleteVideo(Long videoId) throws IOException {
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("vedio", videoId.toString());
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

    Boolean addVedioContentToEs(VideosContent videosContent){
        VideosContentDoc videosContentDoc = new VideosContentDoc(videosContent);
        // 3.将Doc转json
        String json = JSON.toJSONString(videosContentDoc);

        // 1.准备Request对象
        IndexRequest request = new IndexRequest("vedio").id(videosContent.getId().toString());
        // 2.准备Json文档
        request.source(json, XContentType.JSON);
        // 3.发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            return false;
        }
        return true;
    }


}
